package com.xyrl.project.app.controller.common;

import com.xyrl.common.core.controller.BaseController;
import com.xyrl.common.util.ObjectUtil;
import com.xyrl.project.app.util.ShiroUtil;
import com.xyrl.project.common.base.vo.ResponseData;
import com.xyrl.project.common.common.service.AttachmentService;
import com.xyrl.project.common.common.vo.AttachmentVo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.List;

/**
 * 附件上传工具类（阿里oss）
 *
 * @author zhongp
 * @version 1.0
 * @className OssController
 * @company 星纭融链科技服务有限公司
 * @date 2019-12-27 09:44:28
 * @Description
 */
@Slf4j
@Validated
@RestController
@RequestMapping("alioss")
@Api(value = "附件上传", tags = "公共模块")
public class AliOssController extends BaseController {
//    @Autowired
//    private ResourceLoader resourceLoader;

    @Autowired
    private AttachmentService attachmentService;


    /**
     * @param file 要上传的文件
     * @return
     */
    @PostMapping("fileUpload")
    public ResponseData upload(@RequestParam("fileName") MultipartFile file, @NotBlank(message = "文件模块不能为空") String module) {
        log.info("文件上传模块:{}", module);
        try {
            AttachmentVo attachment = attachmentService.addAttachment(file, ShiroUtil.loginUserId(), ShiroUtil.loginInfo().getUserType(), module);
            return ResponseData.success(attachment);
        } catch (Exception e) {
            return ResponseData.error(e.getMessage());
        }
    }

    /**
     * @param files 要上传的文件
     * @return
     */
    @PostMapping("batchFileUpload")
    public ResponseData uploads(@RequestParam("fileNames") MultipartFile[] files, @NotBlank(message = "文件模块不能为空") String module) {
        log.info("文件上传模块:{}", module);
        try {
            if (ObjectUtil.isNotEmpty(files)) {
                List<AttachmentVo> lists = new ArrayList<>();
                for (MultipartFile file : files) {
                    AttachmentVo attachment = attachmentService.addAttachment(file, ShiroUtil.loginUserId(), ShiroUtil.loginInfo().getUserType(), module);
                    attachment.setFileName(file.getOriginalFilename());
                    lists.add(attachment);
                }
                return ResponseData.success(lists);
            }
            return ResponseData.error("附件不能为空");
        } catch (Exception e) {
            return ResponseData.error(e.getMessage());
        }
    }
}
